<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Event;
use App\Events\debug\Debug;
use App\Events\log\AllLog;
use App\Events\noti\Inform;
use App\Models\Area;
use App\Models\Building;
use App\Models\Room;
use Cache;

use Storage;

class LorahelpController extends Controller
{
    public function index(Request $request){
        //Storage::disk('local')->put('file.txt', json_encode($info));
        $data = $request->all();
        /*$data = [
                  "hd" => [
                    "ver" => "0"
                    "rdTk" => "1234"
                    "pktp" => 0
                    "gwad" => "T6CN470S0019"
                  ]
                  "rxpk" => [
                    "time" => "2018-06-05T18:31:20.030515Z"
                    "tmst" => "1528194680"
                    "freq" => 472.1
                    "datr" => "SF12BW125"
                    "rssi" => "-105.0"
                    "lsnr" => "2.5"
                    "chan" => 3
                    "mote" => [
                      "DevE" => "1000000000000001"
                      "DevA" => 268435457
                      "AppE" => "BB02000000AB1112"
                      "fcnt" => 132
                      "fprt" => 8
                      "fmtp" => 4
                      "data" => "EdEAAOI="
                      "datar" => "11d10000e2"
                    ]
                  ]
                  "action" => "app_data"
                ];*/
        $rxpk = $request->input('rxpk'); //消息内容
        $rxpk = array_merge(array_pop($rxpk),$rxpk);
        if (!(Cache::has('mlog'.$rxpk['DevE']))) {
            Cache::put('mlog'.$rxpk['DevE'],true,3);
            $type = DB::table('type')->select('name','id')->where('AppEUI',$rxpk['AppE'])->first();
            if (!empty($type)) {
                $tabletype = '';
                $mark = true;
                // 获取要查询的表名称
                switch ($type['name'])
                {
                    case '烟感':
                        $tabletype = 'smoke';
                        break;
                    case '红外':
                        $tabletype = 'infrared';
                        break;
                    case '呼救':
                        $tabletype = 'help';
                        break;
                    case '燃气':
                        $tabletype = 'gas';
                        break;
                    case '电气':
                        $tabletype = 'electric';
                        break;
                    default:
                        $mark = false;
                }
                if ($mark) {
                    $where = array();
                    $where['tb.DevEUI'] = $rxpk['DevE'];
                    // 查询设备信息
                    $raw = DB::table($tabletype.' as tb')
                        -> leftJoin('room as r','tb.room_id','=','r.id')
                        -> leftJoin('building as b','r.building_id','=','b.id')
                        -> leftJoin('area as a','b.area_id','=','a.id')
                        -> leftJoin('model as m','tb.model_id','=','m.id')
                        -> leftJoin('camera as c','tb.camera_id','=','c.id')
                        -> select('tb.num','tb.agent_id','tb.DevEUI','tb.status','tb.room_id','tb.loc','r.name as rname','r.building_id','b.name as bname','b.latitude','b.longitude','b.area_id','a.name as aname','m.parse','c.url')
                        -> where($where)
                        -> first();
                    // 如果设备存在
                    if ($raw) {
                        if ($raw['status'] == 1) {
                            $pregJson = Storage::get($raw['parse']);
                            $preg = json_decode($pregJson,true);
                            // 解析数据
                            //$msg = $this->analysis($rxpk['datar']);
                            $msgdata = $raw;
                            $msgdata['type'] = $type['name'];
                            if(strlen($rxpk['datar'])>4){
                                $msgdata['genre'] = '呼救';
                            }else{
                                if(substr($rxpk['datar'],0,1) == 0){
                                    if(substr($rxpk['datar'],2,1) == 0){
                                        $msgdata['genre'] = '呼救';
                                    }else{
                                        $msgdata['genre'] = '呼救紧急';
                                    }
                                }
                            }

                            $users = array();
                            $busers = array();
                            $users['bemail'] = array();
                            $users['bphone'] = array();
                            $users['bmobile'] = array();
                            $noti = DB::table('noti_set')->get();
                            // 获取用户信息
                            // $area = Area::where('id',$raw['area_id'])->first()->member()->orderBy('name')->get();
                            $area = Area::where('id',$raw['area_id']) -> first();
                            if ( (!empty($area)) && (!empty($area->member)) ){
                                foreach ($area->member as $areaUsers) {
                                    if ($areaUsers->name) {
                                        array_push($busers,$areaUsers->name);
                                    }
                                    // 邮箱
                                    if (($noti['2']['noti_area']==1)&&($areaUsers->email)) {
                                        array_push($users['bemail'],$areaUsers->email);
                                    }
                                    // 短信
                                    if (($noti['0']['noti_area']==1)&&($areaUsers->phone)) {
                                        array_push($users['bphone'],$areaUsers->phone);
                                    }
                                    // 语音
                                    if (($noti['1']['noti_area']==1)&&($areaUsers->phone)) {
                                        array_push($users['bmobile'],$areaUsers->phone);
                                    }
                                }
                            }
                            $building = Building::where('id',$raw['building_id'])->first();
                            if( (!empty($building) ) && (!empty($building->member)) ) {
                                foreach ($building->member as $buildingUsers) {
                                    if ($buildingUsers->name) {
                                        array_push($busers,$buildingUsers->name);
                                    }
                                    // 邮件
                                    if (($noti['2']['noti_building']==1)&&($buildingUsers->email)) {
                                        array_push($users['bemail'],$buildingUsers->email);
                                    }
                                    // 短信
                                    if (($noti['0']['noti_building']==1)&&($buildingUsers->phone)) {
                                        array_push($users['bphone'],$buildingUsers->phone);
                                    }
                                    // 语音
                                    if (($noti['1']['noti_building']==1)&&($buildingUsers->phone)) {
                                        array_push($users['bmobile'],$buildingUsers->phone);
                                    }
                                }
                            }
                            $room = Room::where('id',$raw['room_id'])->first();
                            if( (!empty($room)) && (!empty($room->member)) ) {
                                foreach ($room->member as $roomUsers) {
                                    if ($roomUsers->name) {
                                        array_push($busers,$roomUsers->name);
                                    }
                                    // 邮件
                                    if (($noti['2']['noti_room']==1)&&($roomUsers->email)) {
                                        array_push($users['bemail'],$roomUsers->email);
                                    }
                                    // 短信
                                    if (($noti['0']['noti_room']==1)&&($roomUsers->phone)) {
                                        array_push($users['bphone'],$roomUsers->phone);
                                    }
                                    // 语音
                                    if (($noti['1']['noti_room']==1)&&($roomUsers->phone)) {
                                        array_push($users['bmobile'],$roomUsers->phone);
                                    }
                                }
                            }

                            // workerman
                            $msgdata['user'] = array_pop($busers);
                            $userphone = $users['bphone'];
                            // $msgdata['phone'] = substr_replace(array_pop($userphone),"****",3,4);
                            $msgdata['phone'] = array_pop($userphone);
                            $data_json = json_encode($msgdata);
                            unset($msgdata['user'],$msgdata['phone']);
                            // 指明给谁推送，为空表示向所有在线用户推送
                            $to_uid = "777iot";
                            // 推送的url地址，使用自己的服务器地址
                            $push_api_url = "http://lot.iqykj.com:2121/";
                            $post_data = array(
                                "type" => "publish",
                                "content" => $data_json,
                                "to" => $to_uid,
                            );
                            $ch = curl_init ();
                            curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
                            curl_setopt ( $ch, CURLOPT_POST, 1 );
                            curl_setopt ( $ch, CURLOPT_HEADER, 0 );
                            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
                            curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
                            curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
                            $return = curl_exec ( $ch );
                            curl_close ( $ch );
                            var_export($return);

                            // 通知
                            Event::fire(new Inform($msgdata,$users,$noti));

                            // 全部消息
                            $msgdata['time'] = $rxpk['tmst'];
                            (int)$number = $rxpk['lsnr']*100;
                            if( $number < -1000 ){
                                $msgdata['lsnr'] = 1;
                            }elseif((-1000 <= $number) && ($number< 0)){
                                $msgdata['lsnr'] = 2;
                            }elseif((0 <= $number) && ($number < 1000)){
                                $msgdata['lsnr'] = 3;
                            }elseif(1000 <= $number){
                                $msgdata['lsnr'] = 4;
                            }
                            Event::fire(new AllLog($msgdata));
                        }
                    }
                }
            }
            // debug
            Event::fire(new Debug($data));
        }
    }
}